package com.youmingxing.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youmingxing.R;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * JHS
 * 2015/12/27
 */

public class WorksCommitGuideActivity extends BaseActivity implements View.OnClickListener {

    private static int VIDEO_PICK = 0;
    private static int PHOTO_PICK = 1;
    private static int TAKE_PHOTO = 2;
    private static int UPLOAD = 3;

    private TextView guidePictures;
    private TextView guideVideos;
    private TextView guideCamera;
    private TextView commitguideHint;
    private ImageView guideImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_worksguid_succeed);
        initView();
        SelfInfoApi.getGuideInfo(new BaseJsonHandler(this) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                JSONObject data = response.optJSONObject("data");
                Glide.with(WorksCommitGuideActivity.this).load(data.optString("img"))
                        .animate(R.anim.abc_fade_in).into(guideImg);
                commitguideHint.setVisibility(View.VISIBLE);
                commitguideHint.setText(data.optString("tip"));
            }
        });
    }

    private void initView() {
        setTopbarName("发布新作品");
        guidePictures = (TextView) findViewById(R.id.guide_pictures);
        guideVideos = (TextView) findViewById(R.id.guide_videos);
        guideCamera = (TextView) findViewById(R.id.guide_camera);
        commitguideHint = (TextView) findViewById(R.id.commit_guide_hint);
        guideImg = (ImageView) findViewById(R.id.commit_guide_img);

        guidePictures.setOnClickListener(this);
        guideVideos.setOnClickListener(this);
        guideCamera.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.guide_pictures:
                PhotoPickerIntent intentPP = new PhotoPickerIntent(this);
                intentPP.setPhotoCount(1);
                intentPP.setShowCamera(false);
                intentPP.setShowGif(true);
                startActivityForResult(intentPP, PHOTO_PICK);
                break;
            case R.id.guide_videos:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "video/*");
                startActivityForResult(intent, VIDEO_PICK);
                break;
            case R.id.guide_camera:
//                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //"android.media.action.IMAGE_CAPTURE";
//                startActivityForResult(intent, TAKE_PHOTO);
                takePhoto();
                break;

        }
    }

    private static final int TAKE_PICTURE = 0x000000;
    private String path = "";
    public void takePhoto()
    {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File vFile = new File(Environment.getExternalStorageDirectory()
                + "/myimage/", String.valueOf(System.currentTimeMillis())
                + ".jpg");
        if (!vFile.exists())
        {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        }
        else
        {
            if (vFile.exists())
            {
                vFile.delete();
            }
        }
        path = vFile.getPath();
        Uri cameraUri = Uri.fromFile(vFile);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        startActivityForResult(openCameraIntent, TAKE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == Activity.RESULT_OK && requestCode != UPLOAD) {
                Intent intent = new Intent();
                intent.setClass(this, UploadActivity.class);
                if (requestCode == TAKE_PHOTO) {
//                    Bundle bundle = data.getExtras();
//                    //获取相机返回的数据，并转换为图片格式
//                    Bitmap bitmap = (Bitmap) bundle.get("data");
//                    String path = Util.saveImageToGallery(WorksCommitGuideActivity.this, bitmap);
                    intent.putExtra("type", PHOTO_PICK);
                    ArrayList<String> photo = new ArrayList<>();
                    photo.add(path);
                    intent.putExtra("photo_array", photo);
                } else if (requestCode == VIDEO_PICK) {
                    try {
                        Uri selectedImage = data.getData();
                        String str = selectedImage.toString();
                        String filePath;
                        if (str.startsWith("file")) {
                            //返回的是文件地址
                            filePath = str.replace("file://", "");
                        } else {
//                        //返回的是uri类型
//                        Uri selectedImage = data.getData();
                            String[] filePathColumn = {MediaStore.Images.Media.DATA};
                            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                            cursor.moveToFirst();
                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            filePath = cursor.getString(columnIndex);
                            cursor.close();

                        }
                        intent.putExtra("type", VIDEO_PICK);
                        intent.putExtra("path", filePath);
                    } catch (Exception e) {
                        Log.e("Demo", "choose file error!", e);
                    }
                } else if (requestCode == PHOTO_PICK) {
                    ArrayList<String> photos =
                            data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    intent.putExtra("type", PHOTO_PICK);
                    intent.putExtra("photo_array", photos);
                }
                startActivityForResult(intent, UPLOAD);
            }
            if (resultCode == Activity.RESULT_OK && requestCode == UPLOAD) {
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

